<?php
/**
 * Override or insert variables into the html template.
 */
function adminsosyuki_preprocess_html(&$vars) {
  // Add theme name to body class.
  $vars['classes_array'][] = 'adminsosyuki-theme';
  $vars['classes_array'][] = 'style-checkboxes';
  $vars['classes_array'][] = 'adminsosyuki-skin-default';

  // Remove the no-sidebars class which is always added by core. Core assumes
  // the sidebar regions are called sidebar_first and sidebar_second, which
  // is not the case in this theme.
  $key = array_search('no-sidebars', $vars['classes_array']);
  if ($key !== FALSE) {
    unset($vars['classes_array'][$key]);
  }
  // Add information about the number of sidebars.
  if (!empty($vars['page']['sidebar_left']) && !empty($vars['page']['sidebar_right'])) {
    $vars['classes_array'][] = 'two-sidebars';
  }
  elseif (!empty($vars['page']['sidebar_left'])) {
    $vars['classes_array'][] = 'one-sidebar sidebar-left';
  }
  elseif (!empty($vars['page']['sidebar_right'])) {
    $vars['classes_array'][] = 'one-sidebar sidebar-right';
  }
  else {
    $vars['classes_array'][] = 'no-sidebars';
  }
}

function _adminsosyuki_load_menu($menu_name) {
  $menu = (array) menu_tree_page_data($menu_name);
  $items = [];
  foreach ($menu as $data) {
    if ($data['link']['access'] && !$data['link']['hidden']) {
      $items[] = $data;
    }
  }
  return _adminsosyuki_serialize_data($items);
}

function _adminsosyuki_serialize_data($items) {
  $build = [];
  foreach ($items as $i => $data) {
    if (!$data['link']['access'] || $data['link']['hidden']) {
      continue;
    }
    $item = new stdClass();
    $item->link = (object) $data['link'];
    $item->link->active = 0;
    $item->link->path = url($data['link']['link_path']);

    if ($data['link']['link_path'] == current_path()) {
      $item->link->active = 1;
    }

    $item->link->class = "";
    if (!empty($data['link']['options']['attributes']['class']) &&
      is_array($data['link']['options']['attributes']['class'])
    ) {
      foreach (($data['link']['options']['attributes']['class']) as $class) {
        $item->link->class .= " {$class}";
      }
    }

    $item->link->url_alias = $item->link->path;
    switch ($data['link']['link_path']) {
      case "<nolink>":
      case "<separator>":
      case "<front>":
        {
          $item->link->url_alias = "";
          break;
        }
    }

    if (!empty($data['below'])) {
      $item->children = _adminsosyuki_serialize_data($data['below']);
      $c_active = 0;
      foreach ($item->children as $child) {
        if ($child->link->active) {
          $c_active = 1;
          break;
        }
      }
      if ($c_active == 1) {
        $item->link->active = $c_active;
      }
    }
    else {
      $item->children = [];
    }

    $build[$item->link->title . ' | ' . $item->link->mlid] = $item;
  }
  return $build;
}

/**
 * Override or insert variables into the page template.
 */
function adminsosyuki_preprocess_page(&$vars) {
  $vars['primary_local_tasks'] = $vars['tabs'];
  $styles = [
    'btn-primary',
    'btn-info',
    'btn-success',
    'btn-warning',
    'btn-danger',
  ];
  foreach ($vars['action_links'] as $i => &$link) {
    unset($link['#theme']);
    $link['#link']['localized_options']['attributes']['class'][] = 'btn';
    $link['#link']['localized_options']['attributes']['class'][] = $styles[$i];
    $link['#link']['localized_options']['attributes']['class'][] = 'shiny';
    $link['#markup'] = adminsosyuki_get_url($link['#link']);
  }
  unset($vars['page']['hidden']);

  unset($vars['primary_local_tasks']['#secondary']);
  $vars['secondary_local_tasks'] = [
    '#theme' => 'menu_local_tasks',
    '#secondary' => $vars['tabs']['#secondary'],
  ];
  unset($vars['page']['hidden']);


  $menu_name = variable_get('adminsosyuki_sidebar_left_menu', 'menu-admin-menu');
  if (!empty($menu_name)) {
    $menu = menu_load($menu_name);
    if (!empty($menu)) {
      $menus = _adminsosyuki_load_menu($menu_name);
      $vars['sidebar_menu'] = $menus;
    }
  }
}

function adminsosyuki_password($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'password';
  $element['#attributes']['class'][] = 'form-control';

  element_set_attributes($element, ['id', 'name', 'size', 'maxlength']);
  _form_set_class($element, ['form-text']);

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

function adminsosyuki_textfield(&$variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'text';
  element_set_attributes($element, [
    'id',
    'name',
    'value',
    'size',
    'maxlength',
  ]);
  _form_set_class($element, ['form-text']);


  $element['#attributes']['class'][] = 'form-control';

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input'])) {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = [];
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#autocomplete_input']['#id'];
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';

  return $output . $extra;
}

function adminsosyuki_textarea($variables) {
  $element = $variables['element'];
  element_set_attributes($element, ['id', 'name', 'cols', 'rows']);
  _form_set_class($element, ['form-textarea']);

  $wrapper_attributes = [
    'class' => ['form-textarea-wrapper'],
  ];

  // Add resizable behavior.
  if (!empty($element['#resizable'])) {
    drupal_add_library('system', 'drupal.textarea');
    $wrapper_attributes['class'][] = 'resizable';
  }
  $element['#attributes']['class'][] = 'form-control';
  $output = '<div' . drupal_attributes($wrapper_attributes) . '>';
  $output .= '<textarea' . drupal_attributes($element['#attributes']) . '>' . check_plain($element['#value']) . '</textarea>';
  $output .= '</div>';
  return $output;
}

function adminsosyuki_menu_local_tasks(&$variables) {
  $output = '';

  if (!empty($variables['primary'])) {
    $variables['primary']['#prefix'] = '<h5 class="element-invisible">' . t('Primary tabs') . '</h5>';
    $variables['primary']['#prefix'] .= '<ul class="nav nav-tabs">';
    $variables['primary']['#suffix'] = '</ul>';
    $output .= drupal_render($variables['primary']);
  }
  if (!empty($variables['secondary'])) {
    $variables['secondary']['#prefix'] = '<h5 class="element-invisible">' . t('Secondary tabs') . '</h5>';
    $variables['secondary']['#prefix'] .= '<ul class="nav nav-tabs tabs-flat">';
    $variables['secondary']['#suffix'] = '</ul>';
    $output .= drupal_render($variables['secondary']);
  }

  return $output;
}

function adminsosyuki_menu_local_task(&$variables) {
  $link = $variables['element']['#link'];
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', [
      '!local-task-title' => $link['title'],
      '!active' => $active,
    ]);
  }

  return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";
}

function adminsosyuki_get_url($link) {
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', [
      '!local-task-title' => $link['title'],
      '!active' => $active,
    ]);
  }
  //btn btn-link
  //  dpm($link['localized_options']);
  return l($link_text, $link['href'], $link['localized_options']);
}

/**
 * Display a view as a table style.
 */
function adminsosyuki_preprocess_views_view_table(&$vars) {
  $vars['classes_array'] = [
    'views-table',
    'table',
    'table-hover',
    'table-striped',
    'table-bordered',
  ];
  //  table table-hover table-striped table-bordered
}

function adminsosyuki_table($variables) {
  $header = $variables['header'];
  $rows = $variables['rows'];
  $attributes = $variables['attributes'];
  $caption = $variables['caption'];
  $colgroups = $variables['colgroups'];
  $sticky = $variables['sticky'];
  $empty = $variables['empty'];

  // Add sticky headers, if applicable.
  if (count($header) && $sticky) {
    drupal_add_js('misc/tableheader.js');
    // Add 'sticky-enabled' class to the table to identify it for JS.
    // This is needed to target tables constructed by this function.
    $attributes['class'][] = 'sticky-enabled';
  }

  $attributes['class'][] = 'table';
  $attributes['class'][] = 'table-hover';
  $attributes['class'][] = 'table-striped';
  $attributes['class'][] = 'table-condensed';
  //  table table-hover table-striped table-bordered
  $output = '<table' . drupal_attributes($attributes) . ">\n";

  if (isset($caption)) {
    $output .= '<caption>' . $caption . "</caption>\n";
  }

  // Format the table columns:
  if (count($colgroups)) {
    foreach ($colgroups as $number => $colgroup) {
      $attributes = [];

      // Check if we're dealing with a simple or complex column
      if (isset($colgroup['data'])) {
        foreach ($colgroup as $key => $value) {
          if ($key == 'data') {
            $cols = $value;
          }
          else {
            $attributes[$key] = $value;
          }
        }
      }
      else {
        $cols = $colgroup;
      }

      // Build colgroup
      if (is_array($cols) && count($cols)) {
        $output .= ' <colgroup' . drupal_attributes($attributes) . '>';
        $i = 0;
        foreach ($cols as $col) {
          $output .= ' <col' . drupal_attributes($col) . ' />';
        }
        $output .= " </colgroup>\n";
      }
      else {
        $output .= ' <colgroup' . drupal_attributes($attributes) . " />\n";
      }
    }
  }

  // Add the 'empty' row message if available.
  if (!count($rows) && $empty) {
    $header_count = 0;
    foreach ($header as $header_cell) {
      if (is_array($header_cell)) {
        $header_count += isset($header_cell['colspan']) ? $header_cell['colspan'] : 1;
      }
      else {
        $header_count++;
      }
    }
    $rows[] = [
      [
        'data' => $empty,
        'colspan' => $header_count,
        'class' => ['empty', 'message'],
      ],
    ];
  }

  // Format the table header:
  if (count($header)) {
    $ts = tablesort_init($header);
    // HTML requires that the thead tag has tr tags in it followed by tbody
    // tags. Using ternary operator to check and see if we have any rows.
    $output .= (count($rows) ? ' <thead><tr>' : ' <tr>');
    foreach ($header as $cell) {
      $cell = tablesort_header($cell, $header, $ts);
      $output .= _theme_table_cell($cell, TRUE);
    }
    // Using ternary operator to close the tags based on whether or not there are rows
    $output .= (count($rows) ? " </tr></thead>\n" : "</tr>\n");
  }
  else {
    $ts = [];
  }

  // Format the table rows:
  if (count($rows)) {
    $output .= "<tbody>\n";
    $flip = ['even' => 'odd', 'odd' => 'even'];
    $class = 'even';
    foreach ($rows as $number => $row) {
      // Check if we're dealing with a simple or complex row
      if (isset($row['data'])) {
        $cells = $row['data'];
        $no_striping = isset($row['no_striping']) ? $row['no_striping'] : FALSE;

        // Set the attributes array and exclude 'data' and 'no_striping'.
        $attributes = $row;
        unset($attributes['data']);
        unset($attributes['no_striping']);
      }
      else {
        $cells = $row;
        $attributes = [];
        $no_striping = FALSE;
      }
      if (count($cells)) {
        // Add odd/even class
        if (!$no_striping) {
          $class = $flip[$class];
          $attributes['class'][] = $class;
        }

        // Build row
        $output .= ' <tr' . drupal_attributes($attributes) . '>';
        $i = 0;
        foreach ($cells as $cell) {
          $cell = tablesort_cell($cell, $header, $ts, $i++);
          $output .= _theme_table_cell($cell);
        }
        $output .= " </tr>\n";
      }
    }
    $output .= "</tbody>\n";
  }

  $output .= "</table>\n";
  return $output;
}